package com.et.common.controller;

import android.app.Application;
import android.os.AsyncTask;

public abstract class BaseController {

	public final static int RESPONSE_STATE_OK = 1;
	public final static int RESPONSE_STATE_ERR = 0;
	
	protected Application ctx;
	protected BaseModleChangeListener changeListener;
		
	public BaseController(Application context,BaseModleChangeListener listener) {
		super();
		ctx = context;
		this.changeListener = listener;
	}
	/**
	 * 通知来自视图组件的监听器模型组件数据已经改变
	 * @param action 请求代码
	 * @param state 请求处理状态代码
	 * @param value 返回结果
	 */
	private void notifyChange(int action,int state,Object value){
		if (changeListener!=null) {
			changeListener.onModleChanged(action,state,value);
		}
	}
	
	/**
	 * 发送同步请求
	 * @param action 请求代码
	 * @param parames 请求参数
	 */
	public void sendRequest(int action,Object parames){
		try {
			Object value = handleRequest(action, parames);
			notifyChange(action, RESPONSE_STATE_OK,value);
		} catch (Exception e) {
			Object value = handleRequest(action, parames);
			notifyChange(action, RESPONSE_STATE_ERR,value);
		}		
	}
	/**
	 * 发送异步请求
	 * @param action 请求代码
	 * @param parames 请求参数
	 */
	public void sendAsyncRequest(final int action,final Object parames){
		
		new AsyncTask<Object, Void, Object>() {
			@Override
			protected Object doInBackground(Object... params) {
				try {
					return handleRequest(action, parames);
				} catch (Exception e) {
					return e;
				}
			}
			@Override
			protected void onPostExecute(Object result) {
				if (result instanceof Exception) {
					notifyChange(action, RESPONSE_STATE_ERR, result);
					return;
				}
				notifyChange(action, RESPONSE_STATE_OK, result);
			}
		}.execute(parames);
	}
	/**
	 * 用于具体处理不同请求的方法，由子类实现
	 * @param action 请求代码
	 * @param parames 请求参数
	 * @return 处理请求后的结果
	 */
	protected abstract Object handleRequest(int action,Object parames);
		
}
